<template>
  <view>
    <up-avatar size="60" :src="avatar" @click="selectFile"></up-avatar>
    <t-cropper
      mode="ratio"
      :imageUrl="cutImageUrl"
      :width="500"
      :height="500"
      :delay="150"
      :radius="500"
      @cancel="onCancel"
      @confirm="onConfirm"
    ></t-cropper>
  </view>
</template>

<script lang="ts" setup>
import { useUserStore } from '@/store/modules/user';
const userStore = useUserStore();
const emit = defineEmits(['update:modelValue']);

const loadingStatus = ref(false);

const uploadImgUrl = ref('/resource/oss/upload'); // 上传的图片服务器地址
const headers = ref(globalHeaders());
const avatar = ref(userStore.avatar);
const cutImageUrl = ref(null);


const selectFileData = ref(null);
const selectFile = async () => {
  const selectRes = await uni.chooseImage({ count: 1 });
  // const compressRes = await uni.compressImage({ src: selectRes.tempFilePaths[0], quality: 80 });
  cutImageUrl.value = selectRes.tempFilePaths[0];
  selectFileData.value = selectRes.tempFiles[0];
};

// 关闭裁剪
const onCancel = () => {
  cutImageUrl.value = null;
};

// 裁剪确认
const onConfirm = async (cutRes) => {
  cutImageUrl.value = null;
  const reader = new FileReader();
  reader.onloadend = () => {
    avatar.value = reader.result as string;
  };
  reader.readAsDataURL(cutRes.tempFilePath);
  const oss = await uni?.$u?.http?.upload(uploadImgUrl.value, {
    // #ifndef H5
    filePath: cutRes.tempFilePath,
    // #endif
    // #ifdef H5
    file: cutRes.tempFilePath,
    // #endif
    name: 'file'
  });
  emit('update:modelValue', oss.data.ossId);
  selectFileData.value = null;
};
</script>

<style scoped lang="scss">

</style>
